import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class LuceneIndexCreateTest {
    @Test
    public void testCreateIndex() throws IOException {
        //创建文档集合
        Collection<Document> doc=new ArrayList<>();
        //目录对象
        Directory directory= FSDirectory.open(new File("indexDir"));//创建目录对象
        //文档对象
        Document document1=new Document();//创建文档对象
        //为文档添加可以创建索引的字段
        document1.add(new TextField("name","陈真大战虹口道场，一站成名", Field.Store.YES));
        document1.add(new StringField("id","1", Field.Store.YES));
        doc.add(document1);
        Document document2=new Document();
        document2.add(new StringField("id","2", Field.Store.YES));
        document2.add(new TextField("name","陈真大胜四国武士", Field.Store.YES));
        doc.add(document2);
        //分词器对象
        Analyzer analyzer=new IKAnalyzer();
        //索引写入器配置对象
        IndexWriterConfig config=new IndexWriterConfig(Version.LATEST,analyzer);
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        //索引写入对象
       IndexWriter indexwrite=new IndexWriter(directory,config);
        //写入索引目录
        indexwrite.addDocuments(doc);
        //提交
        indexwrite.commit();
        //关闭
        indexwrite.close();


    }
    @Test
    public void testSearch() throws IOException, ParseException {
        //获取索引目录对象
        Directory directory=FSDirectory.open(new File("indexDir"));
        //获取读取索引的对象
        IndexReader reader= DirectoryReader.open(directory);
        //获取搜索索引的对象
        IndexSearcher searcher=new IndexSearcher(reader);
        //查询转换工具，用来转换对象
        QueryParser parser=new QueryParser("name",new IKAnalyzer());
        //获得搜索条件对象
        Query query = parser.parse("陈真大");
        //用户的搜索条件
        TopDocs topDocs = searcher.search(query, 2);
        System.out.println("命中的条数"+topDocs.totalHits);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        System.out.println("真正查到的数量"+scoreDocs.length);
        for (ScoreDoc scoreDoc : scoreDocs) {
            //获取文档的编号
            int docID=scoreDoc.doc;
            //获取文档的得分
            float socre=scoreDoc.score;
            System.out.println(docID+"---------"+socre);
            //根据文档的编号去获取文档
            Document doc = searcher.doc(docID);
            System.out.println("查询得到的id"+doc.get("id"));
            System.out.println("查询得到的name"+doc.get("name"));
        }
    }
    public void Search(Query query) throws IOException {
        // 索引目录对象
        Directory directory = FSDirectory.open(new File("indexDir"));
        // 索引读取工具
        IndexReader reader = DirectoryReader.open(directory);
        // 索引搜索工具
        IndexSearcher searcher = new IndexSearcher(reader);

        // 搜索数据,两个参数：查询条件对象要查询的最大结果条数
        // 返回的结果是 按照匹配度排名得分前N名的文档信息（包含查询到的总条数信息、所有符合条件的文档的编号信息）。
        TopDocs topDocs = searcher.search(query, 2);
        // 获取总条数
        System.out.println("本次搜索共找到" + topDocs.totalHits + "条数据");
        // 获取得分文档对象（ScoreDoc）数组.SocreDoc中包含：文档的编号、文档的得分
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        for (ScoreDoc scoreDoc : scoreDocs) {
            // 取出文档编号
            int docID = scoreDoc.doc;
            // 获取文档得分
            float score = scoreDoc.score;
            // 根据编号去找文档
            Document doc = searcher.doc(docID);

            String id = doc.get("id");
            String name = doc.get("name");

            System.out.println("score: " + score +"id: " + id +"name: " + name);
        }
    }
    @Test
    public void testTermQuery() throws IOException {
        //创建词条查询对象
        TermQuery query = new TermQuery(new Term("name", "陈真"));
        Search(query);
    }
    @Test
    public void testWildCardQuery() throws IOException {
        //创建通配符查询
        WildcardQuery query = new WildcardQuery(new Term("name", "*"));
        Search(query);
    }

}
